package com.xxl.job.executor.service.jobhandler;

import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.test.LoginDevice;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;

import Acs.Kqlsgl;



/**
 * XxlJob开发示例（Bean模式）
 *
 * 开发步骤： 1、任务开发：在Spring Bean实例中，开发Job方法； 2、注解配置：为Job方法添加注解
 * "@XxlJob(value="自定义jobhandler名称", init = "JobHandler初始化方法", destroy =
 * "JobHandler销毁方法")"，注解value值对应的是调度中心新建任务的JobHandler属性的值。 3、执行日志：需要通过
 * "XxlJobHelper.log" 打印执行日志； 4、任务结果：默认任务结果为 "成功"
 * 状态，不需要主动设置；如有诉求，比如设置任务结果为失败，可以通过 "XxlJobHelper.handleFail/handleSuccess"
 * 自主设置任务结果；
 *
 * @author xuxueli 2019-12-11 21:52:51
 */
@Component
public class DeviceXxlJob {
	private static Logger logger = LoggerFactory.getLogger(DeviceXxlJob.class);

	/**
	 * 5、生命周期任务示例：任务初始化与销毁时，支持自定义相关逻辑；
	 */
	@Resource // 自动注入，spring boot会帮我们实例化一个对象
	private JdbcTemplate commonDao; // 一个通过JDBC连接数据库的工具类，可以通过这个工具类对数据库进行增删改查
	
	@XxlJob(value = "multiJobHandler", init = "init", destroy = "destroy")
	public void multiJobHandler() throws Exception {
		logger.info("====================================================================================================================================================================================================================================================================================================================================================================任务启动"+new Date().toLocaleString()+"=================================================");
//		DefaultQueryFilter queryFilter = new DefaultQueryFilter(true);
		boolean istest = false;
		istest=false;	
		String sql = "select * from kqsbgl where sfyx =1";
		List<Map<String, Object>> list = commonDao.queryForList(sql);

		String serversql="select * from kqfwqgl where sfyx>0";
		List<Map<String, Object>> serverlist = commonDao.queryForList(serversql);

  		List<DeviceThread> treadlist=new ArrayList<DeviceThread>();
		DeviceThread.ontime.clear();
		for(int i=0;i<serverlist.size();i++)
		{
			
			Map json=serverlist.get(i);
			String serverip=json.get("ip").toString();
			String port=json.get("port").toString();
			DeviceThread callback  = new DeviceThread(serverip,port,list,commonDao);
 			Thread thread = new Thread(callback,serverip);
	        thread.start();  
	        Thread.sleep(2000);
	        treadlist.add(callback);
		}
		boolean iscontinue=true;
		while (iscontinue){
			for(int i=0;i<treadlist.size();i++)
			{
				DeviceThread callback=treadlist.get(i);
	            if(callback.getResult()!=null){
	                logger.info("execute check up info : " + callback.getResult());

	            	treadlist.remove(i);
	               i--;
	            }
			}
			if(treadlist.size()==0)
				break;
			else
				if(list.size()==0)
				{
					Thread.sleep(50000);
					break;
				}
            // 定时检测、提高一下性能
            Thread.sleep(1000);
		}
		String sqlgen="insert into zz_kqjltemp (`kqsj`, `gh`, `xh`, `xm`, `bc`, `bcid`, `sbdk2`, `xbdk2`, `leftsb`, `leftxb`, `leftsb2`, `leftxb2`, `kqrq`, `id_`,`dqsj`) SELECT `kqsj`, `gh`, `xh`, `xm`, `bc`, `bcid`, `sbdk2`, `xbdk2`, `leftsb`, `leftxb`, `leftsb2`, `leftxb2`, `kqrq`, `id_`,`dqsj` FROM `v_dataall`";
		commonDao.execute(sqlgen);
		sqlgen="update tyzt set dqsj= (select max(dqsj) from zz_kqjltemp ) where tybz='tempgen'";
		commonDao.execute(sqlgen);

		logger.info("ip count: " + list.size());
//		allDataJobHandler.execute("all");
 
	}

	@XxlJob(value = "deviceJobHandler", init = "init", destroy = "destroy")
	public void deviceJobHandler() throws Exception {
		XxlJobHelper.log("XXL-JOB, Hello World.");
		String m_sUsername = "admin";// 设备用户名
		String m_sPassword = "1234567a";// 设备密码
		short wport = 8000;
		String fromTime = "2021-06-02 00:00:00";
		String toTime = "2021-09-03 12:00:00";
		String ip = "192.168.1.107";
		String recodetime = "";
		try {

			List<Map<String, Object>> deviceList = commonDao.queryForList("select * from kqsbgl where sfyx =1");
			Map device = null;
			while(true) {

			for (int i = 0; i < deviceList.size(); i++) {
				try {
					LoginDevice treat = new LoginDevice();

					device = deviceList.get(i);
//					deviceList.remove(0);

					Object obj = device.get("zhkqsj");
//				String sbid = (String) device.get("id_");
					ip = (String) device.get("ip");
System.out.println(i+"---------------------------"+ip);
//					Calendar calendar = Calendar.getInstance();
					if (obj != null)
						fromTime = obj.toString().replace(".0", "");
					else
						fromTime = new SimpleDateFormat("yyyy-MM-dd 00:00:00").format(new Date().getTime());
					SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
					if (format.parse(fromTime).getTime() > new Date().getTime())
						continue;

					String currtime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date().getTime());

//				LoginDevice treat = new LoginDevice();
//				 fromTime = "2021-06-02 00:00:00";
//				 toTime = "2021-09-03 12:00:00";
//				 ip = "192.168.1.107";
					List<Kqlsgl> list2 = null;

					try {
						list2 = treat.treatDevice(ip, m_sUsername, m_sPassword, wport, fromTime, currtime);
						if (list2 == null)
							continue;
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
						continue;
					}
					if (list2.size() == 0)
						continue;
					int ii = 0;// 从切换班开始调试

					String mSql = "";
					Kqlsgl temp;
					int count = 0;

					for (; ii < list2.size(); ii++) {
						temp = list2.get(ii);

						if (list2.get(ii).getGh() == null)
							continue;

						recodetime = temp.getSj();
						if (count == 10) {
							mSql = "insert into sbxxsj (id_,sbip,gh,kqsj,seq,dqsj) values " + mSql;
							commonDao.execute(mSql);
							mSql = "";
							count = 0;
						} else
							count++;
						/*
						 * 插入数据库 1、拼接sql，每10条数据一条sql语句执行存储
						 */
						if (mSql != "")
							mSql += ",";
						mSql += "('" + currtime + "-" + temp.getGh() + ii + "','" + ip + "','" + temp.getGh() + "','"
								+ temp.getSj() + "'," + ii + ",'" + currtime + "')";
					}
					mSql = "insert into sbxxsj (id_,sbip,gh,kqsj,seq,dqsj) values " + mSql;
					commonDao.execute(mSql);
					// 记录日志
					String endtime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format((new Date()).getTime());

//					mSql = "insert into kqsblog (id_,sbip,kszxsj,jszxsj,sjjzsj,jls) values ('" + currtime + ip + "','"
//							+ ip + "','" + currtime + "','" + endtime + "','" + recodetime + "','" + list2.size()
//							+ "')";
//
//					commonDao.execute(mSql);
					// 保存打卡时间
					mSql = "update kqsbgl set zhkqsj='" + recodetime + "',tbsj='" + endtime + "' where ip='" + ip + "'";
					commonDao.execute(mSql);
					XxlJobHelper
							.log("ip:" + ip + " fromtime:" + fromTime + " list count:" + list2.size() + "sql:" + mSql);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					continue;
				}
			}
			Thread.sleep(300000);
			}
		} catch (Exception e) {
			e.printStackTrace();
			return;
		}

		
		
		
	}

	public void init() {
		logger.info("init");
	}

	public void destroy() {
		logger.info("destory");
	}

}
